<template>
  <div class="visitor-table">
    <!-- 搜索栏：只有当 companyId 为 1 时才显示 -->
    <el-form
      v-if="userStore.user?.deptId === 1"
      :inline="true"
      :model="queryForm"
      class="query-form"
    >
      <el-form-item label="公司名称">
        <el-input
          v-model="queryForm.companyName"
          placeholder="请输入公司名称"
          clearable
          class="search-input"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch" :icon="Search"
          >查询</el-button
        >
        <el-button @click="resetForm" :icon="Refresh">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 访客记录列表 -->
    <el-table
      v-loading="loading"
      :data="visitorList"
      border
      style="width: 100%"
      highlight-current-row
      :header-cell-style="{ background: '#f5f7fa' }"
    >
      <template #header>
        <el-button type="primary" @click="dialogVisible = true"
          >新增联系人</el-button
        >
      </template>
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column
        type="index"
        label="序号"
        width="60"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="digitalFingerprint"
        label="访客名称"
        show-overflow-tooltip
      ></el-table-column>

      <el-table-column
        prop="realName"
        label="真实姓名"
        show-overflow-tooltip
      ></el-table-column>

      <el-table-column
        prop="companyName"
        label="公司名称"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-tag size="small" :type="row.companyName ? 'success' : 'info'">
            {{ row.companyName || "未知公司" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="visitTime"
        label="访问时间"
        width="200"
        show-overflow-tooltip
      ></el-table-column>
      <!-- <el-table-column
        prop="createTime"
        label="创建时间"
        width="200"
      ></el-table-column> -->
      <el-table-column
        prop="updateTime"
        label="结束时间"
        width="200"
      ></el-table-column>
      <!-- <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === '1' ? 'success' : 'info'">
            {{ scope.row.status === "1" ? "已联系" : "未联系" }}
          </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <!-- <el-button
            type="primary"
            link
            size="small"
            @click="goToAddForm(row.digitalFingerprint)"
            >添加联系人</el-button
          > -->
          <el-button
            type="primary"
            link
            size="small"
            @click="handleDelete(row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="Number(total)"
      :current-page="Number(currentPage)"
      :page-size="Number(pageSize)"
      :page-sizes="[10, 20, 50, 100]"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <!-- 新增联系人对话框 -->
    <el-dialog v-model="dialogVisible" title="新增联系人" width="500px">
      <el-form :model="formData" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="formData.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="formData.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="QQ号">
          <el-input v-model="formData.qq" placeholder="请输入QQ号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import request from "@/utils/request"; // 导入封装的request工具
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/store/modules/user";

const userStore = useUserStore();

const queryForm = ref({
  companyName: "", // 公司名称
});

interface VisitorItem {
  id: number;
  digitalFingerprint: string;
  realName: string;
  companyId: number;
  visitTime: string;
  createTime: string;
  updateTime: string;
}

const visitorList = ref<VisitorItem[]>([]); // 访客列表数据
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const dialogVisible = ref(false);
const formData = ref({
  // visitorId: userStore.user.deptId, // 实例
  visitorId: "123123", // 固定值
  companyId: 12, // 固定值
  name: "",
  phone: "",
  qq: "",
  createBy: 1, // 修改为客服ID
});

const router = useRouter();

// 获取访客列表数据（简化版）
const getVisitorList = async () => {
  loading.value = true;
  try {
    const queryParams = new URLSearchParams({
      page: currentPage.value.toString(),
      size: pageSize.value.toString(),
      companyId: userStore.user?.deptId?.toString() || "0", // 添加可选链和默认值
    });

    if (queryForm.value.companyName.trim()) {
      queryParams.append("companyName", queryForm.value.companyName.trim());
    }

    const { data } = await request.post(
      `/api/v1/visitor/getVisitorPage?${queryParams.toString()}`
    );

    // 更新为新的数据结构
    visitorList.value = data.records || [];
    total.value = data.total || 0;
    currentPage.value = data.current;
    pageSize.value = data.size;
  } catch (error) {
    console.error("请求出错", error);
    ElMessage.error(error.message || "请求出错");
  } finally {
    loading.value = false;
  }
};

// 查询按钮点击事件
const handleSearch = () => {
  currentPage.value = 1;
  getVisitorList();
};

// 重置按钮点击事件
const resetForm = () => {
  queryForm.value.companyName = "";
  currentPage.value = 1;
  handleSearch();
};

// 删除按钮点击事件
const handleDelete = (id) => {
  ElMessageBox.confirm("确定删除这条记录吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const res = await request.delete(`/api/v1/visitor/delete/${id}`);
      if (res.code === "200") {
        ElMessage.success("删除成功");
        getVisitorList(); // 删除成功后重新加载数据
      } else {
        ElMessage.error("删除失败");
      }
    } catch (error) {
      console.error("删除请求出错", error);
    }
  });
};

// 已联系按钮点击事件
const handleContact = (row) => {
  ElMessageBox.confirm("确定将该记录标记为已联系吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
  }).then(async () => {
    try {
      const response = await request.post(
        `/api/v1/contact/updateStatus`,
        null,
        {
          params: { id: row.id },
        }
      );
      if (response.code === "200") {
        ElMessage.success("已标记为已联系");
      } else {
        ElMessage.error(response?.message || "操作失败");
      }
    } catch (error) {
      console.error("操作失败", error);
      ElMessage.error("操作失败");
    }
  });
};

// 分页大小改变事件
const handleSizeChange = (val) => {
  pageSize.value = Number(val);
  getVisitorList();
};

// 页码改变事件
const handlePageChange = (val) => {
  currentPage.value = Number(val);
  getVisitorList();
};

// 新增联系人
const handleAdd = async () => {
  try {
    // 表单验证
    if (!formData.value.name.trim()) {
      return ElMessage.warning("请输入姓名");
    }
    if (!formData.value.phone.trim()) {
      return ElMessage.warning("请输入电话");
    }
    if (!formData.value.qq.trim()) {
      return ElMessage.warning("请输入QQ号");
    }

    const response = await request.post("/api/v1/contact/add", formData.value);
    if (response.code === "200") {
      ElMessage.success("新增成功");
      dialogVisible.value = false;
      // 重置表单数据
      formData.value = {
        visitorId: "123123",
        companyId: 12,
        name: "",
        phone: "",
        qq: "",
        createBy: 1,
      };
      getVisitorList(); // 刷新列表
    } else {
      ElMessage.error(response?.message || "新增失败");
    }
  } catch (error) {
    console.error("新增失败:", error);
    ElMessage.error("新增失败");
  }
};

// 页面挂载加载数据
onMounted(() => {
  getVisitorList();
});

// 在访客列表中添加跳转方法
const goToAddForm = (digitalFingerprint: string) => {
  console.log("Row data:", digitalFingerprint);

  if (!digitalFingerprint) {
    ElMessage.warning("访客信息不完整");
    return;
  }

  // 使用 name 进行导航
  router.push({
    name: "MessageAddForm",
    query: { digitalFingerprint },
  });
};
</script>

<style scoped>
.visitor-table {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.query-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #ffffff;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.search-input {
  width: 220px;
}

.el-button {
  margin-right: 10px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #ebeef5;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
  padding: 15px 0;
}

:deep(.el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

:deep(.el-tag) {
  border-radius: 4px;
}
</style>
